package org.example.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.example.annotation.Log;
import org.example.domain.dto.DTO;
import org.example.domain.dto.ErpDepotItemDTO;
import org.example.domain.po.*;
import org.example.domain.vo.ErpDepotHeadRetailVo;
import org.example.domain.vo.ErpDepotItemVO;
import org.example.enums.BusinessType;
import org.example.service.*;
import org.example.service.impl.ErpDepotItemServiceImpl;
import org.example.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@RequestMapping("/retail")
@RestController
public class ErpRetailController {

    @Resource
    private ErpDepotHeadService erpDepotHeadService;
    @Autowired
    private ErpDepotItemServiceImpl erpDepotItemService;
    @Autowired
    private ErpRoleService roleService;
    @Autowired
    ErpMaterialCurrentStockService currentStockService;
    @Autowired
    private ErpmaterialinventoryService erpmaterialinventoryService;
    @PostMapping("/select1")
    public R<Page<ErpDepotHeadRetailVo>> getErpDepotHeadsByPage(@RequestBody Retail retail,   @RequestAttribute("user") ErpUser user){

        Page<ErpDepotHeadRetailVo> page = new Page<>(retail.getCurrent(), retail.getSize());
        try {

            page = erpDepotHeadService.select1(page, retail,user.getTenantId());
            ErpRole role = roleService.getRoleByUserId(user.getId());
            if (StrUtil.contains("5", role.getPriceLimit())){
                List<String> names = Arrays.asList("changeAmount","backAmount","totalPrice");
                page.getRecords().forEach(item -> {
                    DTO.shieldPrice(item, names);
                });
            }
            return R.success(page);
        } catch (Exception e) {
            return R.fail("查询失败：" + e.getMessage());
        }
    }

    @PostMapping("/select2")
    public R<Page<ErpDepotHeadRetailVo>> getselecte2(@RequestBody Retail retail,@RequestAttribute("user") ErpUser user){

        Page<ErpDepotHeadRetailVo> page = new Page<>(retail.getCurrent(), retail.getSize());
        try {

            page = erpDepotHeadService.select2(page, retail,user.getTenantId());
            ErpRole role = roleService.getRoleByUserId(user.getId());
            if (StrUtil.contains("5", role.getPriceLimit())){
                List<String> names = Arrays.asList("changeAmount","backAmount","totalPrice");
                page.getRecords().forEach(item -> {
                    DTO.shieldPrice(item, names);
                });
            }
            return R.success(page);
        } catch (Exception e) {
            return R.fail("查询失败：" + e.getMessage());
        }
    }


    /**
     * 根据主表id查子表详情
     * @param id
     * @return
     */
//    @GetMapping("/findById/{id}")
//    public Result<List<ErpDepotItemVO>> findById(@PathVariable("id") Integer id){
//        List<ErpDepotItemVO> erpDepotItems = erpDepotItemService.findById(id);
//        return Result.success(erpDepotItems);
//    }

    @GetMapping("/findByPageAssociateorder")
    public R<Page<ErpDepotHead>> RetailOut(@RequestParam(defaultValue = "1") Integer current,
                                           @RequestParam(defaultValue = "2") Integer size, String number, String createTime,
                                           String operTime,String standard,Long id,String subType){
        Page<ErpDepotHead> page=new Page<>(current,size);
        try {
            page=erpDepotHeadService.RetailOut(page,number,createTime,operTime,standard,id,subType);
            return R.success(page);
        } catch (Exception e) {
            return R.fail("查询失败：" + e.getMessage());
        }

    }
//    /**
//     * 零售添加
//     * @param depotRequest
//     * @return
//     */
//    @Log(operation = "零售出库添加", businessType = BusinessType.INSERT, isSaveRequestData = true, paramName = "user", jsonPath = "$.username")
//    @PostMapping("/insert")
//    public Result<String> insert(@RequestBody DepotRequest depotRequest,
//                                 @RequestAttribute("user") ErpUser user){
//        int i = erpDepotHeadService.insertPurchase(depotRequest, user);
//        return i > 0 ? Result.success("添加成功") : Result.success("添加失败");
//    }
    /**
     * 零售添加
     * @param depotRequest
     * @return
     */
//    @Log(operation = "零售出库添加", businessType = BusinessType.INSERT, isSaveRequestData = true, paramName = "user", jsonPath = "$.username")
//    @PostMapping("/insert")
//    public Result<String> insert(@RequestBody DepotRequest depotRequest,
//                                 @RequestAttribute("user") ErpUser user) {
//        // 提取出库头和明细
//        ErpDepotHead erpDepotHead = depotRequest.getErpDepotHead();
//        List<ErpDepotItem> erpDepotItems = depotRequest.getErpDepotItems();
//
//        // 设置基本信息
//        erpDepotHead.setCreator(user.getId());
//        erpDepotHead.setTenantId(user.getTenantId());
//        erpDepotHead.setCreateTime(new Date());
//        erpDepotHead.setOperTime(new Date());
//        erpDepotHead.setDefaultNumber(erpDepotHead.getNumber());
//
//        // 保存出库头信息
//        int insertCount = erpDepotHeadService.deprotinsert(erpDepotHead);
//        if (insertCount > 0) {
//            // 获取刚插入的出库头的ID
//            Long headerId = erpDepotHeadService.finbyid(erpDepotHead.getNumber());
//
//            // 遍历并处理每个出库条目
//            for (ErpDepotItem item : erpDepotItems) {
//                item.setTenantId(user.getTenantId());
//                item.setHeaderId(headerId);
//                ErpDepotItemDTO erpDepotItemDTO = BeanUtil.copyProperties(item, ErpDepotItemDTO.class);
//
//                // 保存出库条目信息
//                erpDepotItemService.insertdepot(erpDepotItemDTO);
//
////                // 调入仓库新增库存
////                currentStockService.updateStock(item.getMaterialId(), item.getAnotherDepotId(), item.getOperNumber(), item.getTenantId());
////                // 调出仓库减少库存
////                currentStockService.updateStock(item.getMaterialId(), item.getDepotId(), item.getOperNumber().negate(), item.getTenantId());
//                // 根据类型判断操作
//                if ("入库".equals(erpDepotHead.getType())) {
//                    // 调入仓库新增库存
//                    currentStockService.updateStock(item.getMaterialId(), item.getAnotherDepotId(), item.getOperNumber(), item.getTenantId());
//                    // 调出仓库减少库存（负数的操作变更在入库下不执行，通常只需要增加）
//                } else if ("出库".equals(erpDepotHead.getType())) {
//                    // 调入仓库增加库存（无操作，通常不在出库下做)
//                    // 调出仓库减少库存
//                    currentStockService.updateStock(item.getMaterialId(), item.getDepotId(), item.getOperNumber().negate(), item.getTenantId());
//                }
//            }
//
//            return Result.success("添加成功");
//        } else {
//            return Result.error("添加失败");
//        }
//    }

    /**
     * 零售添加
     * @param depotRequest
     * @return
     */
    @Log(operation = "零售出库添加", businessType = BusinessType.INSERT, isSaveRequestData = true, paramName = "user", jsonPath = "$.username")
    @PostMapping("/insert")
    public Result<String> insert(@RequestBody DepotRequest depotRequest,
                                 @RequestAttribute("user") ErpUser user) {
        // 提取出库头和明细
        ErpDepotHead erpDepotHead = depotRequest.getErpDepotHead();
        List<ErpDepotItem> erpDepotItems = depotRequest.getErpDepotItems();

        // 设置基本信息
        erpDepotHead.setCreator(user.getId());
        erpDepotHead.setTenantId(user.getTenantId());
        erpDepotHead.setCreateTime(new Date());
        erpDepotHead.setOperTime(new Date());
        erpDepotHead.setDefaultNumber(erpDepotHead.getNumber());

        // 保存出库头信息
        int insertCount = erpDepotHeadService.deprotinsert(erpDepotHead);
        if (insertCount > 0) {
            // 获取刚插入的出库头的ID
            Long headerId = erpDepotHeadService.finbyid(erpDepotHead.getNumber());

            // 遍历并处理每个出库条目
            for (ErpDepotItem item : erpDepotItems) {
                item.setTenantId(user.getTenantId());
                item.setHeaderId(headerId);
                ErpDepotItemDTO erpDepotItemDTO = BeanUtil.copyProperties(item, ErpDepotItemDTO.class);

                // 保存出库条目信息
                erpDepotItemService.insertdepot(erpDepotItemDTO);

                // 根据类型判断操作
                currentStockService.updateStock(item.getMaterialId(), item.getDepotId(), item.getOperNumber(), item.getTenantId());
            }

            return Result.success("添加成功");
        } else {
            return Result.error("添加失败");
        }
    }

    @DeleteMapping("/delete/{id}")
    public R<String> deleteRetail(@PathVariable Long id) {
        int result = erpDepotHeadService.deleteRetail(id);
        if (result != 0) {
            return R.success("删除成功");
        } else {
            return R.fail("删除失败");
        }
    }
    @PutMapping("/updateOut")
    public R updateOut(@RequestBody DepotRequest depotRequest, @RequestParam String number) {
        // 获取头部和明细信息
        ErpDepotHead erpDepotHead = depotRequest.getErpDepotHead();
        List<ErpDepotItem> erpDepotItems = depotRequest.getErpDepotItems();



        int headUpdateCount = erpDepotHeadService.updateDepotHead(erpDepotHead,number);
        System.out.println(headUpdateCount);
        System.out.println(number);
        if (headUpdateCount > 0) {

            Long headerId = erpDepotHeadService.lookByHeaderId(number);

            for (ErpDepotItem item : erpDepotItems) {
                ErpDepotItemDTO erpDepotItemDTO = BeanUtil.copyProperties(item, ErpDepotItemDTO.class);
                int itemUpdateCount = erpDepotItemService.updateDepotItem(erpDepotItemDTO,headerId);
                if (itemUpdateCount <= 0) {
                    return R.fail("子表更新失败");
                }
            }
        } else {
            return R.fail("头部更新失败");
        }

        return R.success("更新成功");
    }

    /**
     * 关联查询子单据
     * @param headerId
     * @return
     */
    @GetMapping("/findItem")
    public Result<List<ErpDepotItemVO>> findItems(@RequestParam("headerId") Long headerId){
        List<ErpDepotItemVO> erpDepotItems = erpDepotItemService.findItem(headerId);
        return Result.success(erpDepotItems);
    }


    /**
     * 删除
     * @param id
     * @return
     */
    @DeleteMapping("/remove/{id}")
    public Result<String> remove(@PathVariable("id") Long id){
        boolean b = erpDepotHeadService.removeById(id);
        return b ? Result.success("删除成功") : Result.success("删除失败");
    }


}

